#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


######################################################################################
#	Please DO NOT uck with this file... Or Cron job... please... PLEASE...
#	Ask Balazs if you need something!
######################################################################################

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from string import Template
from google.appengine.ext import db
import header
import footer
from urllib2 import *
import httplib, urllib

from Functions import Functions
from Tweet_model import GeoTweet_model

import time
import datetime
import header
import footer
import urllib2
import simplejson
#import json

class Stalker(webapp.RequestHandler):
	
	# 	DO NOT USE THIS! EVER! NEVER-EVER!
	#def clear_db(self):
		#		  t_database = db.GqlQuery("SELECT * FROM Tweet_model " )
		#
		#		  for p in t_database:
			#			     p.delete()
			
			
			
	def stalk_twitter(self):
		
		
######################################################################################
#	Please DO NOT uck with this file... Or Cron job... please... PLEASE...
#	Ask Balazs if you need something!
######################################################################################

				url_rl = "http://api.twitter.com/1/account/rate_limit_status.json"
				f_rl = urlopen(url_rl)
				rate_limit_status = simplejson.loads(f_rl.read())
				Rem = simplejson.dumps(rate_limit_status["remaining_hits"])
				self.response.out.write("In this hour, we have ")
				self.response.out.write(Rem)
				self.response.out.write(" twitter queries remaining<br>")
				f_rl.close()
				
				locationstring = "northgate+college+station,+tx"	#Later can be modified to dynamic
				latlon = ""
				lat = ""
				lng = ""
				
				url_geocode_gmaps = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false' % (locationstring)	    #google maps api to get lat,lon based on location
				f_geocode_gmaps = urlopen(url_geocode_gmaps)
				while not f_geocode_gmaps:
					f = urlopen(url_geocode_gmaps)
					print "bad"
				results = simplejson.loads(f_geocode_gmaps.read())
				#print results
				for each in results['results']:
					lat = str(each['geometry']['location']['lat'])
					lng = str(each['geometry']['location']['lng'])
					#latlon += str(each['geometry']['location']['lat']) + "," + str(each['geometry']['location']['lng'])
					break        

######################################################################################
#	Please DO NOT uck with this file... Or Cron job... please... PLEASE...
#	Ask Balazs if you need something!
######################################################################################
				
				f_geocode_gmaps.close()
				self.response.out.write("Location Coordinates for %s is %s , %s<br><br>" % (locationstring, lat, lng))
		
				r = "10km"
				url = 'http://search.twitter.com/search.json?&geocode='+lat+','+lng+','+r+'&rpp=20&result_type=recent'
						
				self.response.out.write(url+"<br><br>")
				try:
					result = urllib2.urlopen(url)
					data = simplejson.load(result)
				except urllib2.URLError, e:
						print(e.code)
						print(e.read())
						return
								
				for p in data["results"]:
					m = GeoTweet_model()
									
					duplicate = False
									
					#self.response.out.write(simplejson.dumps(p))
					#self.response.out.write("<br><br>")
					
					m.screen_name = simplejson.dumps(p["from_user_name"])
					m.id_str = simplejson.dumps(p["from_user_id_str"])
					m.real_name = simplejson.dumps(p["from_user_name"])
					if p['geo'] is not None:
						m.geo = str(p['geo']['coordinates'])
					if "location" in p:
						m.location = simplejson.dumps(p["location"])
					
					raw_date = simplejson.dumps(p["created_at"])
					raw_date = raw_date.replace('\"','')
					
					#'Sat, 26 Nov 2011 22:43:57 +0000'
					extracted_date = (time.strptime(raw_date,"%a, %d %b %Y %H:%M:%S +0000"))

######################################################################################
#	Please DO NOT uck with this file... Or Cron job... please... PLEASE...
#	Ask Balazs if you need something!
######################################################################################
									
					m.created_at = datetime.datetime(extracted_date.tm_year,
					extracted_date.tm_mon,
					extracted_date.tm_mday,
					extracted_date.tm_hour,
					extracted_date.tm_min,
					extracted_date.tm_sec
					)
							
					m.text = simplejson.dumps(p["text"])
					m.text = m.text[:500]

					m.put()
					#try:
					#	for _t in t_database:
					#		if(m.text == _t.text or p['geo'] is not None):
					#			duplicate = True
								#return
						#	if(not duplicate):
					
					#	self.response.out.write("NO DUP INSERT")
								#return
					#except:
					#		self.response.out.write("EXCEPT INSERT")
					#		m.put()
											
	def get(self):

######################################################################################
#	Please DO NOT uck with this file... Or Cron job... please... PLEASE...
#	Ask Balazs if you need something!
######################################################################################

		self.response.out.write(header.head)
		self.response.out.write('''  
		<div class="content">
		<div class="content_resize">
		
		<div class="article">
		<div class="clr"></div>
		'''   )     
		
		
		self.stalk_twitter()
		fun = Functions()
		#stalkthis = fun.stalk_NG()
		#self.response.out.write(stalkthis) 
		
		self.response.out.write('''
		</div>
		</div>
		<div class="sidebar">
		<div class="gadget">
		
		<div class="clr"></div>
		
		</div>
		<div class="gadget">
		<div class="clr"></div>
		</ul>
		</div>
		</div>
		<div class="clr"></div>
		</div>
		</div>
		<div class="fbg">
		<div class="fbg_resize">
		<div class="col c1">
		</div>
		<div class="col c3">
		</div>
		<div class="clr"></div>
		</div>
		</div>''')		
		self.response.out.write(footer.foot)
																
if __name__ == '__main__':
	main()